package com.ruoyi.stuclient.utils.aliyunUtil;

import com.aliyun.credentials.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;

@Component
public class SMSUtil {
    @Value("${aliyun.sms.url}")
    public String url;

    @Value("${aliyun.sms.accessKey}")
    public String accessKey;

    @Value("${aliyun.sms.secretKey}")
    public String secretKey;

    @Value("${aliyun.sms.signName}")
    public String signName;

    @Value("${aliyun.sms.templateCode}")
    public String templateCode;

    private static final SecureRandom SECURE_RANDOM = new SecureRandom();

    /**
     * <p>生成6位验证码</p>
     * @return String
     */
    @NotNull
    public static String secureRandom6() {
        return String.format("%06d", SECURE_RANDOM.nextInt(1000000));
    }

    /**
     * <b>description</b> :
     * <p>使用凭据初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        Client credential = new Client();
        Config config = new Config().setCredential(credential);
        config.endpoint = url;
        config.accessKeyId = accessKey;
        config.accessKeySecret = secretKey;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public SendSmsResponse sendSMSCode(String mobileNo, String verifyCode) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = this.createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(mobileNo)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam("{\"code\":\""+verifyCode+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        SendSmsResponse resp = null;
        try {
            resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return resp;
    }

}
